package com.ck.core.util;

import com.alibaba.fastjson.JSONObject;
import com.ck.core.constant.ClientConstant;
import com.ck.core.constant.NormalStrConstant;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ajax请求相关常量
 *
 * @author linqiang
 * @version v1.0
 * @date 2018-10-24 15:30
 */
public class AjaxUtils {

    /**
     * 判断是否是ajax请求
     *
     * @param request 请求
     * @return
     */
    public static boolean isAjax(HttpServletRequest request) {
        boolean isAjax = false;
        if (request.getHeader(NormalStrConstant.X_REQUESTED_WITH) != null
                && NormalStrConstant.XML_HTTP_REQUEST.equals(request.getHeader(NormalStrConstant.X_REQUESTED_WITH))) {
            isAjax = true;
        }
        return isAjax;
    }

    /**
     * 未登录时对ajax请求的处理
     *
     * @param response 响应
     */
    public static void writeNeedLoginResultForAjax(HttpServletResponse response, String loginUrl) throws IOException {
        JSONObject result = new JSONObject();
        result.put("code", ClientConstant.CODE_NOT_LOGIN);
        result.put("msg", "登录超时，请重新登录");
        result.put("data", loginUrl);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(result.toJSONString());
        response.flushBuffer();
    }
}
